package com.example.demo.controller;

import com.example.demo.common.ServerResponse;
import com.example.demo.dao.StudentRepository;
import com.example.demo.domain.Student;
import com.example.demo.exception.StudentException;
import com.example.demo.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created by gf on 2018/10/14.
 */
@RestController
@RequestMapping(value = "/student")
public class StudentController {

    private static Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private StudentService studentService;

    /**
     * 添加
     * @return
     */
    @PostMapping(value = "/add")
    public ServerResponse<Student> addStudent(@Valid Student student,
                                              BindingResult bindingResult){
        if(bindingResult.hasErrors())
            return ServerResponse.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
        return ServerResponse.createBySuccessData(studentRepository.save(student));
    }

    @PostMapping(value = "/add_two")
    public List<Student> transactionTest()throws Exception{
        return studentService.insertStudent();
    }

    /**
     * 查询list
     * @return
     */
    @GetMapping(value = "/list")
    public List<Student> getList(){
        return studentRepository.findAll();
    }

    /**
     * 根据Id查找
     * @param id
     * @return
     */
    @GetMapping(value = "/list/id/{id}")
    public Map<String,Object> queryById(@PathVariable("id") String id){
        Map<String,Object> mv = new HashMap<String,Object>();
        Optional<Student> student = studentRepository.findById(id);
        if (student.isPresent()==false){
            mv.put("code",0);
            mv.put("desc","无此条记录");
            return mv;
        }
            mv.put("code",1);
            mv.put("desc","success");
            mv.put("obj",student);
            return mv;
    }

    /**
     * 更新
     * @return
     */
    @PostMapping(value = "/edit/{id}")
    public Map<String,Object> edit(@PathVariable("id") String id,
                                   @RequestParam("name") String name,
                                   @RequestParam("age") Integer age){
        Map<String,Object> mv = new HashMap<String,Object>();
        if (id==null){
            mv.put("code",0);
            mv.put("desc","请求参数有误");
            return mv;
        }
        if(((int)queryById(id).get("code"))==0){
            mv.put("code",0);
            mv.put("desc","无此条记录");
            return mv;
        }
        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setAge(age);

        mv.put("code",1);
        mv.put("obj",studentRepository.save(student));
        return mv;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping(value = "/remove")
    public Map<String,Object> delete(@RequestParam(value = "id") String id){
        Map<String,Object> mv = new HashMap<String,Object>();
        if(((int)queryById(id).get("code"))==0){
            mv.put("code",0);
            mv.put("desc","无此条记录");
            return mv;
        }
            studentRepository.deleteById(id);
            mv.put("code",1);
            mv.put("desc","success");
            return mv;
    }

    @GetMapping(value = "/list/age/{age}")
    public List<Student> queryByAge(@PathVariable(value = "age") Integer age){
        return studentRepository.findByAge(age);
    }

    @PostMapping(value = "/list/by_age")
    public ServerResponse<List<Student>> queryByAge2(@RequestParam(value = "age") Integer age) throws StudentException {
        return studentService.findByAge(age);
    }

}
